const db = uniCloud.database()
const dbCmd = db.command;
const uniID = require('uni-id')
const {
	smsConfig
} = require('config')
module.exports = {
	main: async (event) => {
		let {
			res,
			token,
			data,
			action
		} = event;
		switch (action) {
			case 'adminLogin':
				res = await adminLogin(data);
				break
			case 'query':
				res.data = await getData(data);
				break;
			case 'edit':
				res = await editData(data);
				break;
			case 'register':
				res = await addShop(data);
			    break;
			case 'login':
			    res = await uniID.login(data);
			    break;
			case 'loginBySms':
			    res.data = await uniID.loginBySms(data);
			    break;
			case 'wxLogin':
			    res.data = await uniID.loginByWeixin(data.code);
			    break;
			case 'bindMobile':
			    res.data = await uniID.bindMobile(data);
			    break;
			case 'checkToken':
			    res.data = await uniID.checkToken(data.token);
			    break;
			case 'sendSmsCode':
				data.templateId = smsConfig.templateId
				res = await uniID.sendSmsCode(data);
				break;
			case 'getUserInfo':
				res.data = await uniID.getUserInfo(data);
				break;
			case 'verifyCode':
				res = await uniID.verifyCode(data);
				break;
			case 'logout':
			    res = await uniID.logout(token);
			    break;
			case 'updateUser':
				res.data = await uniID.updateUser(data);
				break;
			default:
				res = {
					code: 402,
					msg: '非法访问'
				}
				break;
		}
		return res;
	}
}
/**
 * 管理员登录
 */
async function adminLogin(data) {
	let res = {}
	let r1 = await db.collection('admin')
		.where({
			username: data.username,
			password: data.password
		}).count()
	if (r1.total > 0) {
		let r2 = await uniID.login(data)
		if (r2.code > 0) {
			res = await uniID.register(data)
		} else {
			res = r2;
		}
	} else {
		res.code = 402;
		res.msg = "用户名或密码错误";
	}
	return res
}
/**
 * 获取列表数据
 */
async function getData(data) {	
	const result = await db.collection('uni-id-users')
		.where({
			username: dbCmd.neq('admin'),
			userInfo: {
				nickName: eval('/' + data.name + '/')
			},
			register_date: dbCmd.gte(Date.parse(data.startDate)-28800000).and(dbCmd.lte(Date.parse(data.endDate) + 86400000 - 28800000))
		})
		.skip((data.page-1)*data.limit)
		.limit(data.limit)
		.orderBy('register_date', 'desc')
		.get()
	const resultTotal = await db.collection('uni-id-users')
		.where({
			username: dbCmd.neq('admin'),
			userInfo: {
				nickName: eval('/' + data.name + '/')
			},
			register_date: dbCmd.gte(Date.parse(data.startDate)-28800000).and(dbCmd.lte(Date.parse(data.endDate) + 86400000 - 28800000))
		})
		.count()
	
	let res = {
		total:resultTotal.total,
		records:result.data
	}
	return res
}
/**
 * 更新数据
 */
async function editData(data) {
	var res = {}
	const r1 = await db.collection('admin').where({
		username: data.username,
		password: data.oldPwd
	}).count()
	if (r1.total > 0) {
		const result = await db.collection('admin').where({
			username: data.username
		}).update({
			password: data.newPwd,
			updatetime: data.updatetime
		})
		if (result.updated > 0) {
			res.code = 200;
			res.data = '更新数据成功';
			let tmp = {
				uid: data.uid,
				oldPassword: data.oldPwd,
				newPassword: data.newPwd,
				passwordConfirmation: data.newPwd
			}
			await uniID.updatePwd(tmp);
		} else {
			res.code = 402;
			res.msg = '保存失败，请重新操作'
		}
	} else {
		res.code = 402;
		res.msg = '旧密码输入错误'
	}
	return res;
}
/**
 * @param {Object} data
 * 注册添加店铺
 */
async function addShop(data){
	let res = {}
	res = await uniID.register(data);
	if(res.code==0){
		//添加店铺
		const shopRes = await db.collection('shop').add({
			userId: res.uid,
			shopName: '',
			updatetime: new Date().getTime()
		})
		//添加默认页面
		const pageResOne = await db.collection('page').add({
			comType: 'splb',
			diyData: [],
			pageTitle: '商品',
			updatetime: new Date().getTime()
		})
		const pageResTwo = await db.collection('page').add({
			comType: 'gwc',
			diyData: [],
			pageTitle: '购物车',
			updatetime: new Date().getTime()
		})
		const pageResThree = await db.collection('page').add({
			comType: 'wd',
			diyData: [],
			pageTitle: '我的',
			updatetime: new Date().getTime()
		})
		const diyData = [{
			"id": "d9vqptds9yg0000000",
			"name": "title",
			"maintitle": "欢迎体验zxshop",
			"titleStyle": "5",
			"subtitle": "请进入后台-页面管理设计属于您自己的商城吧",
			"textColor": "#ff5622",
			"backgroundColor": "#f9f9f9",
			"signColor": "#3399FF",
			"toUrl": "",
			"comType": ""
		}]
		const pageResFour = await db.collection('page').add({
			comType: 'index',
			templateName: '空白模板',
			diyData: diyData,
			pageTitle: '首页',
			pageShareDetail: '',
			backgroundColor: '#F9F9F9',
			template: 0,
			updatetime: new Date().getTime()
		})
		//添加tabbar
		const tab = [{ 
						"iconIndex": 0, 
						"id": "31bc74ayhmu000", 
						"name": "首页", 
						"toUrl": {
							"id":pageResFour.id,
							"pageTitle":"首页",
							"comType": "index"
						} 
					}, { 
						"iconIndex": 1, 
						"id": "21u4chim2lxc00", 
						"name": "购物车", 
						"toUrl": {
							"id":pageResTwo.id,
							"pageTitle":"购物车",
							"comType":"gwc"
						} 
					}, { 
						"iconIndex": 2, 
						"id": "4qcqk7wmd12000", 
						"name": "我的", 
						"toUrl": {
							"id":pageResThree.id,
							"pageTitle":"我的",
							"comType":"wd"
						} 
					}]
		const tabbarRes = await db.collection('tabbar').add({
			data: tab,
			updatetime: new Date().getTime()
		})
		//添加图片默认分组
		const imgGroupRes = await db.collection('source_group').add({
			name: '未分组',
			type: 1,
			updatetime: new Date().getTime()
		})
		//添加默认设置
		const set = {
					"shopName":"zxshop",
					"shopUrl" :"https://vkceyugu.cdn.bspapp.com/VKCEYUGU-zxshop/1e0ddc20-1ce7-11eb-81ea-f115fe74321c.jpg",  //前台小程序码url
					"adminH5Url": "https://vkceyugu.cdn.bspapp.com/VKCEYUGU-zxshop/a2b68be0-1cdb-11eb-8a36-ebb87efcf8c0.png",   //后台h5URl
					"pay":"微信支付",
					"delivery":"快递发货",
					"adminQrCodeUrl":""
				}
		const settingRes = await db.collection('setting').add({
			data: set,
			updatetime: new Date().getTime()
		})
		//添加默认积分设置
		const point = {
					"onePoint": "0",
					"signInSend": "0",
					"sevenDaySend": "0",
					"toMoney": "关闭"
				}
		const pointRes = await db.collection('point').add({
			data: point,
			updatetime: new Date().getTime()
		})
	}
	return res;
}
